package bm.sg.net.ssf.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 * 类说明：
 * 
 * Modify Information:
 * Author         Date         Description
 * ============ =========== ============================
 * zhoufan      2016-12-20    Create this file
 * 
 * </pre>
 * 
 */
public class FileUtil {
    public static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");


    /**
     * <pre>
     * 方法说明：
     * </pre>
     * 
     * @param string
     * @return
     */
    public static List<String> file2ListString(String path) {
        return file2ListString(new File(path));
    }


    /**
     * 读取文本格式文件的内容，并按行存入list
     * @param file 想要读取的文件对象
     * @return 返回文件内容list
     */
    public static List<String> file2ListString(File file){
        List<String> rtnList = new ArrayList<String>();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
               rtnList.add(s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return rtnList;
    }
    
    /**
     * 读取文本格式文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String file2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                if (result.length() > 0) {
                    result.append(LINE_SEPARATOR);
                }
                result.append(s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
    /**
     * <pre>
     * 方法说明：
     * </pre>
     * 
     * @param string
     * @return
     */
    public static String file2String(String path) {
        return file2String(new File(path));
    }  

    
    /**
     * 方法说明：获取直接子目录名称列表
     * 
     * @param path
     * @return
     */
    public static List<String> getChildDirs(String path) {
        File file = new File(path);
        File [] files = file.listFiles();
        List<String> nameList = new ArrayList<String>();
        for(File f:files) {
            if(f.isDirectory()) {
                nameList.add(f.getName());
            }
        }
        return nameList;
    }
    
    /**
     * <pre>
     * 方法说明：获取文件夹下指定suffix后缀的文件名，不遍历子文件夹
     * </pre>
     * 
     * @param path
     * @param suffix
     * @return
     */
    public static List<String> getNamesWithSuffix(String path, String suffix) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(path);
        // 获取jar名
        String [] names = file.list(new SuffixNameFilter(suffix));
        if(names != null) {
            fileNames.addAll(Arrays.asList(names));
        }
        return fileNames;
    }
    
    /**
     * <pre>
     * 方法说明：获取文件夹下指定prefix前缀、suffix后缀的文件名，不遍历子文件夹
     * </pre>
     * 
     * @param path
     * @param prefix
     * @param suffix
     * @return
     */
    public static List<String> getNames(String path, String prefix, String suffix) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(path);
        // 获取jar名
        String [] names = file.list(new PreSufNameFilter(prefix, suffix));
        if(names != null) {
            fileNames.addAll(Arrays.asList(names));
        }
        return fileNames;
    }
    
    /**
     * 方法说明：遍历所有目录及子目录，获取jar包名称
     * 
     * @param path
     * @return
     */
    public static List<String> getAllJarName(String path) {
        List<String> fileNames = new ArrayList<String>();
        
        File file = new File(path);
        // 获取jar名
        String [] names = file.list(new JarNameFilter());
        if(names != null) {
            fileNames.addAll(Arrays.asList(names));
        }
        
        // 遍历子目录
        File [] files = file.listFiles();
        for(File f:files)
        {
            if(f.isDirectory())
            {
                fileNames.addAll( getAllJarName(f.getAbsolutePath()) );
            }
        }
        return fileNames;
    }
    
    
    /**
     * <pre>
     * 方法说明：广度优先遍历所有子目录，获取非文件夹的绝对路径的路径名
     * </pre>
     * 
     * @param path
     * @return
     */
    public static List<String> getAllFileNameWithoutDir(String path) {
        List<String> rtnList = new ArrayList<String>();
        File file = new File(path);
        if (file.isDirectory()) {
            File [] files = file.listFiles();
            for (File f : files) {
                rtnList.addAll(getAllFileNameWithoutDir(f.getAbsolutePath()));
            }
        } else {
            rtnList.add(file.getAbsolutePath());
        }
        return rtnList;
    }
    
    
    /**
     * 方法说明：广度优先遍历所有子目录，获取全部文件名列表
     * 
     * @param path
     * @return
     */
    public static List<String> getAllFileNames(String path) {
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();
        List<String> fileNames = new ArrayList<String>();
        if(names != null) {
            fileNames.addAll(Arrays.asList(names));

        }
        for(File f:files)
        {
            if(f.isDirectory())
            {
                fileNames.addAll( getAllFileNames(f.getAbsolutePath()) );
            }
        }
        return fileNames;
    }
    
    /**
     * <pre>
     * 类说明：同时根据前缀、后缀过滤文件名
     * 
     * Modify Information:
     * Author         Date         Description
     * ============ =========== ============================
     * zhoufan      2017-07-03    Create this file
     * 
     * </pre>
     * 
     */
    public static class PreSufNameFilter  implements FilenameFilter{
        
        private String prefix;
        private String suffix;
        
        /**
         * 方法说明：
         * 
         */
        public PreSufNameFilter(String prefix, String suffix) {
            this.prefix = prefix;
            this.suffix = suffix;
        }

        /**
         * <pre>
         * 方法说明：
         * </pre>
         *
         * @param dir
         * @param name
         * @return
         * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
         */
        @Override
        public boolean accept(File dir, String name) {
            if (StringUtil.isNotEmpty(name) && name.startsWith(this.prefix) && name.endsWith(this.suffix)) {
                return true;
            }
            return false;
        }
        
    }
    
    /**
     * <pre>
     * 类说明：获取指定Suffix文件名
     * 
     * Modify Information:
     * Author         Date         Description
     * ============ =========== ============================
     * zhoufan      2017-06-10    Create this file
     * 
     * </pre>
     * 
     */
    public static class SuffixNameFilter implements FilenameFilter{
        private String suffix;
        /**
         * 方法说明：指定后缀名，例如“.jar”
         * 
         */
        public SuffixNameFilter(String suffix) {
            this.suffix = suffix;
        }
        
        /**
         * 方法说明：
         *
         * @param dir
         * @param name
         * @return
         * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
         */
        @Override
        public boolean accept(File dir, String name) {
            if(StringUtil.isNotEmpty(name) && name.endsWith(this.suffix)) {
               return true;
            }
            return false;
        }  
    }
    
    /**
     * <pre>
     * 类说明：取jar包文件名
     * 
     * Modify Information:
     * Author         Date         Description
     * ============ =========== ============================
     * zhoufan      2016-12-21    Create this file
     * 
     * </pre>
     * 
     */
    public static class JarNameFilter implements FilenameFilter{  
        /**
         * 方法说明：
         *
         * @param dir
         * @param name
         * @return
         * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
         */
        @Override
        public boolean accept(File dir, String name) {
            if(name.lastIndexOf('.')>0)
            {
               // get last index for '.' char
               int lastIndex = name.lastIndexOf('.');
               
               // get extension
               String str = name.substring(lastIndex);
               
               // match path name extension
               if(str.equals(".jar"))
               {
                  return true;
               }
            }
            return false;
        }  
    }

}
